package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneException;
import com.atguigu.gulimall.member.exception.UsernameException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberUserLoginVo;
import com.atguigu.gulimall.member.vo.MemberUserRegisterVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberUserRegisterVo vo) {
        MemberDao dao=this.baseMapper;
        MemberEntity entity=new MemberEntity();

//        设置默认的等级
        MemberLevelEntity defaultLevel=memberLevelService.getDefaultLevel();
        entity.setLevelId(defaultLevel.getId());

        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

//        检查用户名和手机号是否唯一
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());

//        存储密码
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);


        dao.insert(entity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneException  {
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, phone));
        if (count > 0){
            throw new PhoneException();

        }

     }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, userName));
        if (count > 0) {
            throw new UsernameException();
        }

    }

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

       MemberDao dao= this.baseMapper;
        MemberEntity entity = dao.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, loginacct)
                .or()
                .eq(MemberEntity::getMobile, loginacct));
        if (entity == null){
//            登录失败，用户不存在
            return null;
        }else{
//            查询数据库的密码
            String passwordDB = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//判读密码是否匹配
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches){
                return entity;
            }
        }

        return null;
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {

        String uid = vo.getUid();
        MemberEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getSocialUid, uid));

        if (entity != null) {
            MemberEntity update = new MemberEntity();
            update.setId(entity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in());

            this.baseMapper.updateById(update);

            entity.setAccessToken(vo.getAccess_token());
            entity.setExpiresIn(vo.getExpires_in());

            return entity;
        } else {
            MemberEntity regiest = new MemberEntity();

            try {
                Map<String, String> map1 = new HashMap<>();
                map1.put("access_token", vo.getAccess_token());
                HttpResponse userInfoResponse = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map1);

                if (userInfoResponse.getStatusLine().getStatusCode() == 200) {

                    String userInfoJson = EntityUtils.toString(userInfoResponse.getEntity());
                    JSONObject jsonObject = JSON.parseObject(userInfoJson);
                    String name = jsonObject.getString("name");

                    regiest.setNickname(name);
                    regiest.setGender(0);

                }
            } catch (Exception e) {
            }

            regiest.setSocialUid(vo.getUid());
            regiest.setAccessToken(vo.getAccess_token());
            regiest.setExpiresIn(vo.getExpires_in());

            this.baseMapper.insert(regiest);
            return regiest;

        }


    }


}